<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/1/20
 * Time: 13:57
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use app\Config;
use PDO;

class Resource extends Model
{
    public $pdo = '';
    public $dbName = '';

    public function __construct()
    {
        $dbms = $this->getConfig('type');     //数据库类型
        $host = $this->getConfig('hostname'); //数据库主机名
        $this->dbName = $this->getConfig('database');    //使用的数据库
        $this->pdo = new PDO("$dbms:host=$host;dbname=$this->dbName", $this->getConfig('username'), $this->getConfig('password'));
    }

    /**
     * 检测数据表是否存在
     * @param string $table
     * @return bool
     */
    public function checkTableExist($table = '')
    {
        $tableName = $table ? $table : self::getTable();
        $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $this->dbName, $this->getConfig('prefix') . $tableName);
        $result = $this->pdo->query($sql);
        if ($result === false) {//表不存在
            return false;
        }
        if (!$result->fetchColumn(0)) {
            return false;
        }
        return true;
    }

    /**
     * 复制表结构
     * @param string $table
     * @param string $newTable
     * @param string $company_id
     * @return bool
     */
    public function copyTable($table = '', $newTable = '', $company_id = '')
    {
        $table = $this->getConfig('prefix') . $table;
        $newTable = $this->getConfig('prefix') . $newTable;
        $sql = sprintf("create table %s like %s", $newTable, $table);
        $result = $this->pdo->query($sql);
        if ($result === false) {
            return false;
        }
        $sql = sprintf("alter table %s comment '%s'", $newTable, '公司-' . $company_id . "_" . $table . '分表');
        $this->pdo->query($sql);
        return true;
    }

    /**
     * id获取资源信息
     * @param string $id
     * @param string $company_id
     * @param string $module
     * @param int $status
     * @param string $user_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getResourceByIds($id = '', $company_id = '', $module = '', $status = 1, $user_id = '')
    {
        //资源表
        $resourceTbale = "resource" . "_" . $company_id;
        if ($this->checkTableExist($resourceTbale) == false) {
            return [];
        }

        $where['id'] = ['in', $id];
        !empty($module) && $where['module'] = $module;
        !empty($user_id) && $where['user_id'] = $user_id;
        $where['status'] = $status;
        return DB::name($resourceTbale)->where($where)->select();
    }

    /********************************* 资源管理 *********************************************/

    /**
     * 根据条件获取资源信息
     * @param array $where
     * @param string $company_id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getResource($where=[], $company_id = ''){
        empty($company_id) && $company_id = isession('company_id');
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        }

        $dataArr = Db::name($newResourceTbale)
            ->where($where)
            ->order('timestamp asc')
            ->group('path')
            ->paginate(15, false, ['query' =>
                [
                    'filename' => get('filename')
                ]]);
        return $dataArr;
    }


    /**
     * 根据path，uid删除资源信息
     * @param array $data
     * @param string $company_id
     * @param string $user_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delOneResource($data = [], $id='',$company_id = '', $user_id = '')
    {
        empty($company_id) && $company_id = isession('company_id');
        empty($user_id) && $user_id = isession('user_id');
        //资源表
        $resourceTbale = "resource" . "_" . $company_id;
        if ($this->checkTableExist($resourceTbale) == false) {
            return false;
        }
        $where['user_id'] = $user_id;
        !empty($data['module']) && $where['module'] = $data['module'];
        !empty($data['path']) && $where['name'] = basename($data['path']);
        !empty($data['path']) && $where['path'] = $data['path'];


        //增加当前公司上传空间
        if (isession('type') == 2) {
            //获取资源数据大小
            $res = Db::name($resourceTbale)->where('id',$id)->find();
            if (checkArr($res) && $res['size'] > 0) {
                $where['original'] = $res['original'];
                $sql = "UPDATE ean_company SET use_capacity = (use_capacity-" . $res['size'] . ") WHERE id=" . $company_id;
                $this->pdo->exec($sql);
            }
        }
        Db::name($resourceTbale)->where($where)->delete();
        return true;
    }

    /**
     * 删除文件夹下面的文件资源数据
     * @param array $where
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delResource($where = [], $company_id = '')
    {
        empty($company_id) && $company_id = isession('company_id');
        //资源表
        $resourceTbale = "resource" . "_" . $company_id;
        if ($this->checkTableExist($resourceTbale) == false) {
            return true;
        }
        //增加当前公司上传空间
        if (isession('type') == 2) {
            //获取资源数据大小
            $sql = Db::table($this->getConfig('prefix') . $resourceTbale)->where($where)->group('path')->buildSql();
            $size = Db::table($sql . 'a')->sum('size');
            if ($size > 0) {
                $sql = "UPDATE ean_company SET use_capacity = (use_capacity-" . $size . ") WHERE id=" . $company_id;
                $this->pdo->exec($sql);
            }
        }
        Db::name($resourceTbale)->where($where)->delete();
        return true;
    }

}